//
// Created by mio on 25-4-14.
//

#include "Acceptor.h"

#include "EventLoop.h"
#include <iostream>

Acceptor::Acceptor(EventLoop* eventloop) : loop_(eventloop), tcp_socket_(new TcpSocket())
{
}

Acceptor::~Acceptor()
{
}

int Acceptor::Listen(std::string ip, uint16_t port)
{
    if (tcp_socket_->GetSocket() > 0)
    {
        tcp_socket_->Close();
    }
    int fd = tcp_socket_->Create();
    channel_ = std::make_shared<Channel>(fd);
    SocketUtil::SetNonBlock(fd);
    SocketUtil::SetReuseAddr(fd);
    SocketUtil::SetReusePort(fd);

    if (!tcp_socket_->Bind(ip, port)) return -1;
    if (!tcp_socket_->Listen(1024)) return -2;

    channel_->SetReadCallback([this](){ this->OnAccept(); });
    channel_->EnableRead();
    loop_->UpdateChannel(channel_);
    return 0;
}

void Acceptor::Close()
{
    if (tcp_socket_->GetSocket() <= 0) return;
    loop_->RemoveChannel(channel_);
    tcp_socket_->Close();
}

void Acceptor::OnAccept()
{
    int fd = tcp_socket_->Accept();
    if (fd > 0)
    {
        std::cout << "new Client\n";
        if (new_connectionCb_)
            new_connectionCb_(fd);
    }
}
